import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { TabsPage } from "../tabs/tabs";
import { ToastController } from 'ionic-angular';
import { LoginProvider } from '../../providers/login/login';
import { HttpErrorResponse } from '@angular/common/http';
import { StorageProvider } from '../../providers/storage/storage';
import { Buffer } from 'buffer';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { NotificationProvider } from '../../providers/notification/notification';

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  private username: string;
  private password: string;
  private remember = false;
  public showPass = false;
  private route:string ;
  myForm;
  public type = 'password';
  public formBuilder: FormBuilder;

  constructor(
    private notification: NotificationProvider,
    public navCtrl: NavController,
    public navParams: NavParams,
    public toastCtrl: ToastController,
    public api: LoginProvider,
    private modalCtrl: ModalController,
    private storage: StorageProvider
  ) {
    /* this.myForm = this.formBuilder.group({
      username: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(6),
        Validators.required
        //Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$') //this is for the letters (both uppercase and lowercase) and numbers validation
      ]))
    }); */
  }

  ionViewDidLoad() {
    //this.navCtrl.push(TabsPage);
    let account = this.storage.getObject('account');
    console.log(account);
    if (JSON.stringify(account) != '{}' && account != null) {
      console.log('自动填充 ' + account.username);
      this.username = account.username;
      this.password = account.password;
      this.remember = true;
    }
  }

  login() {
    let url = this.storage.get('server_url');
    if (!url) {
      //this.showToast("请设置服务器地址");
      this.navCtrl.push('SettingsPage');
      return;
    }
    
    if (this.username.length == 0) {
      this.showToast("请输入账号");
      return;
    }
    if (this.password.length == 0) {
      this.showToast("请输入密码");
      return;
    }
    this.api.login(this.username, new Buffer(this.password).toString('base64')).subscribe(res => {
      let userinfo = res;
      if (res['success']) {
        let data = res['data'];
        this.storage.setObject('userinfo', data.info);
        if (this.remember) {
          console.log('记住密码');
          this.storage.setObject('account', { username: this.username, password: this.password });
        } else {
          this.storage.setObject('account', null);
        }
        this.navCtrl.push(TabsPage);
      } else {
        //res['message']
        this.notification.showToast("请检查账号和密码是否正确");
      }
    },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
         this.navCtrl.push('SettingsPage');//这里请求失败跳转设置界面
        } else {
          //console.log(err);
          this.showToast("请检查服务器路径设置");
        }
      });
  }

  showToast(msg: string) {
    const toast = this.toastCtrl.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

  showPassword() {
    this.showPass = !this.showPass;

    if (this.showPass) {
      this.type = 'text';
    } else {
      this.type = 'password';
    }
  }

  settings() {
    this.navCtrl.push('SettingsPage');
  }


}
